# -*- coding: utf-8 -*-
"""
角色编辑对话框
"""

from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QPushButton,
                             QDialogButtonBox, QTabWidget, QComboBox, QLabel,
                             QListWidget, QListWidgetItem, QInputDialog, QMessageBox,
                             QWidget, QMenu, QLineEdit)
from PySide6.QtCore import Qt

from ..models.character import Character
from .character_manager import CharacterAttributeEditor


class RelationshipDialog(QDialog):
    """关系编辑对话框"""
    
    def __init__(self, available_characters, current_relationships=None, parent=None):
        super().__init__(parent)
        self.available_characters = available_characters
        self.current_relationships = current_relationships or []
        self.selected_character_id = ""
        self.relationship_type = ""
        self.relationship_desc = ""
        
        self.init_ui()
    
    def init_ui(self):
        """初始化界面"""
        self.setWindowTitle("添加角色关系")
        self.setMinimumSize(350, 250)
        
        layout = QVBoxLayout(self)
        
        # 选择角色
        char_layout = QHBoxLayout()
        char_layout.addWidget(QLabel("目标角色:"))
        self.character_combo = QComboBox()
        for char in self.available_characters:
            self.character_combo.addItem(char.name, char.id)
        char_layout.addWidget(self.character_combo)
        layout.addLayout(char_layout)
        
        # 关系类型
        type_layout = QHBoxLayout()
        type_layout.addWidget(QLabel("关系类型:"))
        self.type_combo = QComboBox()
        self.type_combo.setEditable(True)
        self.type_combo.addItems([
            "朋友", "恋人", "夫妻", "父子", "母子", "父女", "母女",
            "兄弟", "姐妹", "师父", "徒弟", "同事", "上司", "下属",
            "敌人", "对手", "盟友", "邻居", "同学", "老师", "学生"
        ])
        type_layout.addWidget(self.type_combo)
        layout.addLayout(type_layout)
        
        # 关系描述
        desc_layout = QVBoxLayout()
        desc_layout.addWidget(QLabel("关系描述:"))
        self.desc_edit = QLineEdit()
        self.desc_edit.setPlaceholderText("可选，描述这种关系的具体情况...")
        desc_layout.addWidget(self.desc_edit)
        layout.addLayout(desc_layout)
        
        # 按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
    
    def get_relationship_data(self):
        """获取关系数据"""
        return {
            'target_id': self.character_combo.currentData(),
            'type': self.type_combo.currentText(),
            'description': self.desc_edit.text()
        }


class CharacterEditDialog(QDialog):
    """角色编辑对话框"""
    
    def __init__(self, character: Character, parent=None):
        super().__init__(parent)
        self.character = character
        # 获取所有角色（用于建立关系）
        self.all_characters = []
        if parent and hasattr(parent, 'novel') and parent.novel:
            self.all_characters = [c for c in parent.novel.characters if c.id != character.id]
        
        self.init_ui()
    
    def init_ui(self):
        """初始化界面"""
        self.setWindowTitle(f"编辑角色 - {self.character.name}")
        self.setMinimumSize(500, 600)
        
        layout = QVBoxLayout(self)
        
        # 创建标签页
        tab_widget = QTabWidget()
        layout.addWidget(tab_widget)
        
        # 基本信息标签页
        self.attr_editor = CharacterAttributeEditor(self.character)
        tab_widget.addTab(self.attr_editor, "基本信息")
        
        # 关系管理标签页
        self.create_relationship_tab(tab_widget)
        
        # 按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
    
    def create_relationship_tab(self, tab_widget):
        """创建关系管理标签页"""
        rel_widget = QWidget()
        layout = QVBoxLayout(rel_widget)
        
        # 工具栏
        toolbar = QHBoxLayout()
        toolbar.addWidget(QLabel("角色关系:"))
        toolbar.addStretch()
        
        add_rel_btn = QPushButton("添加关系")
        add_rel_btn.clicked.connect(self.add_relationship)
        toolbar.addWidget(add_rel_btn)
        
        layout.addLayout(toolbar)
        
        # 关系列表
        self.relationship_list = QListWidget()
        self.relationship_list.setContextMenuPolicy(Qt.CustomContextMenu)
        self.relationship_list.customContextMenuRequested.connect(self.show_rel_context_menu)
        layout.addWidget(self.relationship_list)
        
        # 加载关系
        self.load_relationships()
        
        tab_widget.addTab(rel_widget, "关系管理")
    
    def load_relationships(self):
        """加载关系列表"""
        self.relationship_list.clear()
        
        for rel in self.character.relationships:
            # 查找目标角色名字
            target_name = rel['target_id']
            for char in self.all_characters:
                if char.id == rel['target_id']:
                    target_name = char.name
                    break
            
            item_text = f"{rel['type']} -> {target_name}"
            if rel['description']:
                item_text += f" ({rel['description']})"
            
            item = QListWidgetItem(item_text)
            item.setData(Qt.UserRole, rel)
            self.relationship_list.addItem(item)
    
    def add_relationship(self):
        """添加关系"""
        if not self.all_characters:
            QMessageBox.information(self, "提示", "没有其他角色可以建立关系")
            return
        
        dialog = RelationshipDialog(self.all_characters, self.character.relationships, self)
        if dialog.exec() == QDialog.Accepted:
            rel_data = dialog.get_relationship_data()
            if rel_data['target_id'] and rel_data['type']:
                # 检查是否已存在相同关系
                for existing_rel in self.character.relationships:
                    if (existing_rel['target_id'] == rel_data['target_id'] and 
                        existing_rel['type'] == rel_data['type']):
                        QMessageBox.warning(self, "警告", "该关系已存在！")
                        return
                
                self.character.add_relationship(
                    rel_data['target_id'], 
                    rel_data['type'], 
                    rel_data['description']
                )
                self.load_relationships()
    
    def show_rel_context_menu(self, pos):
        """显示关系右键菜单"""
        item = self.relationship_list.itemAt(pos)
        if item:
            menu = QMenu(self)
            delete_action = menu.addAction("删除关系")
            delete_action.triggered.connect(lambda: self.delete_relationship(item))
            menu.exec(self.relationship_list.mapToGlobal(pos))
    
    def delete_relationship(self, item):
        """删除关系"""
        rel = item.data(Qt.UserRole)
        if rel:
            reply = QMessageBox.question(self, "确认删除", 
                                       f"确定要删除与角色的'{rel['type']}'关系吗？",
                                       QMessageBox.Yes | QMessageBox.No,
                                       QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.character.remove_relationship(rel['target_id'], rel['type'])
                self.load_relationships()
    
    def accept(self):
        """确认编辑"""
        # 保存角色信息
        self.attr_editor.save_character()
        super().accept() 